package com.example.common.utils;

import cn.hutool.core.util.ObjectUtil;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author 王鹤蒲
 * @Date 2023 11 22
 */
public class ListPageUtil {
    public static<T> Map<String,Object> startPage(List<T> list, Integer currentPage, Integer pageSize) {
         Map<String,Object> dataListMap=new HashMap<String,Object>();
        if (ObjectUtil.isEmpty(list)) {
            return dataListMap;
        }
        if (pageSize == 0 || currentPage == 0) {
            return dataListMap;
        }

        // 记录总数
        Integer count = list.size();

        // 页数
        int pageCount = 0;
        if (count % pageSize == 0) {
            pageCount = count / pageSize;
        } else {
            pageCount = count / pageSize + 1;
        }

        // 开始索引
        int fromIndex = 0;
        // 结束索引
        int toIndex = 0;

        fromIndex = (currentPage - 1) * pageSize > count ? Math.max(count - pageSize, 0) : (currentPage - 1) * pageSize;
        if (currentPage != pageCount) {
            toIndex = fromIndex + pageSize > count ? count : fromIndex + pageSize;
        } else {
            toIndex = count;
        }
        dataListMap.put("records",list.subList(fromIndex, toIndex));
        dataListMap.put("total",count);
        return dataListMap;
    }

}
